import React, { Component, Suspense, Fragment } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { ChromePicker } from 'react-color';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Button, Input, Upload, message, Radio, Spin } from 'antd';
import Editor from '@/utils/Editor';
import styles from "./index.less";
import imgURL from '../../../assets/accessSettings/icon-a.png';
import LogoimgURL from '../../../assets/accessSettings/icon-头像.png';
import khmrimgURL from '../../../assets/accessSettings/icon-机器人.png';
import AND from '@/assets/icons/AND.png'
import IOS from '@/assets/icons/IOS.png'

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_fqf69hupewt.js', // 在 iconfont.cn 上生成
});
const { TextArea } = Input;
class AppAccess extends Component {
  constructor() {
    super();
    this.state = {
      yuyhc: '1', // 语音合成
      yuysran: '1', // 语音输入按钮
      color: '#19c3f3',
      displayColorPicker: false,
      logoa: '/robotConfigImg/1.png',
      logob: '/robotConfigImg/2.png',
      logoc: '/robotConfigImg/3.png',
      entranceWebStyle: '', // 入口图标样式 电脑端
      entranceH5Style: '', // 入口图标样式 移动端
      ckbt: '',
      ckys: '',
      jqrkfName: '',
      // 参数结结束
      imageUrld: null,
      imageUrle: null,
      index: null,
      indextwo: null,
      color: '#19c3f3 ',
      displayColorPicker: false,
      loading: false,
      loadingA: false,
      loadingB: false,
      valueA: '1',
      valueB: '1',
      valueC: '1',
      ckdxSize: '1',
      mrckdxweb: '1',
      mrckdxydd: '1',
      commonProblemList: [{ name: '', item: '' }],
      pdxs: true,
      content: '',
      spinning:false
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    this.suax()
  }

  handleChangeComplete = (color) => {

    this.setState({ color: color.hex });
  };

  // ----------- 窗口颜色-----------------------
  handleClick = () => {
    this.setState({ displayColorPicker: !this.state.displayColorPicker })
  };

  handleClose = () => {
    this.setState({ displayColorPicker: false })
  };

  // ----------------客户默认头像----------
  // ----------------客户默认头像----------
  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  beforeUpload = (file) => {

    const isJPG = file.type;
    const isLt2M = file.size / 1024 / 1024 < 1;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJPG && isLt2M;
  }

  handleChangeA = info => {

    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrla =>
        this.setState({
          imageUrla,
          loading: false,
          logob: info.file.response.url
        }),
      );
    }
  };
  // ------------- 解决状态--------------------


  // ------------- 机器人默认头像--------------
  handleChangeB = info => {

    if (info.file.status === 'uploading') {
      this.setState({ loadingA: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrlb =>
        this.setState({
          imageUrlb,
          loadingA: false,
          logoc: info.file.response.url
        }),
      );
    }
  };

  copy = () => {
    let text = document.getElementById('biao1');
      if (document.body.createTextRange) {
          var range = document.body.createTextRange();
          range.moveToElementText(text);
          range.select();
      } else if (window.getSelection) {
          let selection = window.getSelection();
          let range = document.createRange();
          range.selectNodeContents(text);
          selection.removeAllRanges();
          selection.addRange(range);
      }
      document.execCommand('Copy');
    message.success('复制成功！')
  }

  // eslint-disable-next-line react/sort-comp
  render() {
    let {currentUser} = this.props;
    const popover = {
      position: 'absolute',
      zIndex: '2',
    }
    const gbcolor = {
      background: this.state.color,
    }
    const cover = {
      position: 'fixed',
      top: '0px',
      right: '0px',
      bottom: '0px',
      left: '0px',
    }
    const body = '</body>'
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        sm: 24,
        md: 3,
      },
      wrapperCol: {
        sm: 24,
        md: 20
      }
    }
    // 客服头像
    const uploadButton = (
      <img style={{ width: 51, height: 51, borderRadius: '50%' }} src={this.state.logob} />
    );
    // 机器人头像
    const uploadButtona = (
      <img style={{ width: 51, height: 51, borderRadius: '50%' }} src={this.state.logoc} />
    );
    const imageUrla = this.state.imageUrla;
    const imageUrlb = this.state.imageUrlb;
    const imageUrlc = this.state.imageUrlc;
    return (
      <div>
        <Spin spinning={this.state.spinning}>
          <span className={styles.titlep}><span>app接入</span></span>
          <div className={styles.appjr}>
            <div className={styles.webAccess}>
              <img src={AND} />
              <span>iOS SDK下载及接入说明</span>
            </div>
            <div style={{ paddingLeft: 28, paddingRight: 28 }} className={styles.webAccess}>
              <img src={IOS} />
              <span>ANDROID SDK下载及接入说明</span>
            </div>
          </div>
          <div style={{ height: 30 }}></div>
          <span className={styles.titlep}><span>APPKEY</span></span>
          <p style={{ margin: '22px 0px 22px 28px' }}>请将以下代码添加到你网站的HTML源代码中，放在标签{body}之前，即可实现接入</p>
          <div className={styles.textTitleDeV}>
          <div className={styles.textTitle} id="biao1">{currentUser.robotId}</div>
            <Button size='small' onClick={this.copy} className={styles.djBu}>复制</Button>
          </div>
          <div style={{ height: 30 }}></div>
          <span className={styles.titlep}><span>APP接入设置</span></span>
          <div style={{ height: 30 }}></div>
          <div>
            <div>
              <Form layout="horizontal">
                <FormItem label='语音合成' {...FormItemLayont}>
                  {getFieldDecorator('yuyhc', {
                    initialValue: this.state.yuyhc,
                  })(
                    <RadioGroup>
                      <Radio value='1'>开启</Radio>
                      <Radio value='2'>关闭</Radio>
                    </RadioGroup>
                  )}
                </FormItem>
                <FormItem label='语音输入按钮' {...FormItemLayont}>
                  {getFieldDecorator('yuysran', {
                    initialValue: this.state.yuysran,
                  })(
                    <RadioGroup>
                      <Radio value='1'>显示</Radio>
                      <Radio value='2'>隐藏</Radio>
                    </RadioGroup>
                  )}
                </FormItem>
                <FormItem label='窗口颜色' {...FormItemLayont}>
                  {getFieldDecorator('ckcolor', {
                    initialValue: this.state.color,
                  })(
                    <div className={styles.flexColor}>
                      <div style={gbcolor} className={styles.colorzj} onClick={this.handleClick} />
                      <span>{this.state.color}</span>
                      {this.state.displayColorPicker ? <div style={popover}>
                        <div style={cover} onClick={this.handleClose} />
                        <ChromePicker
                          color={this.state.color}
                          onChangeComplete={this.handleChangeComplete}
                        />
                      </div> : null}
                    </div>
                  )}
                </FormItem>
                <FormItem className='Uploadlg' label='客户默认头像' {...FormItemLayont}>
                  <Upload
                    name="avatar"
                    listType="picture"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="/res/upload"
                    beforeUpload={this.beforeUpload}
                    onChange={this.handleChangeA}
                  >
                    <div className={styles.xzwj}>{imageUrla ? <img style={{ width: 51, height: 51, borderRadius: '50%' }} src={imageUrla} alt="avatar" /> : uploadButton}<Button style={{ marginLeft: 10 }} size='small'>选择文件</Button></div>
                  </Upload>
                  <p style={{ fontSize: 10, color: '#99a8b7', marginBottom: 0 }}>标题栏左侧Logo图，大小不超过1MB,推荐图片尺寸50*50</p>
                </FormItem>
                <FormItem label='机器人客服头像' {...FormItemLayont}>
                  <Upload
                    name="customersFace"
                    listType="picture"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="/res/upload"
                    beforeUpload={this.beforeUpload}
                    onChange={this.handleChangeB}
                  >
                    <div className={styles.xzwj}>{imageUrlb ? <img style={{ width: 51, height: 51, borderRadius: '50%' }} src={imageUrlb} alt="customersFace" /> : uploadButtona}<Button style={{ marginLeft: 10 }} size='small'>选择文件</Button></div>
                  </Upload>
                  <p style={{ fontSize: 10, color: '#99a8b7', marginBottom: 0 }}>标题栏左侧Logo图，大小不超过1MB,推荐图片尺寸50*50</p>
                </FormItem>
                <FormItem label='机器人客服名称' {...FormItemLayont}>
                  {getFieldDecorator('jqrkfName', {
                    initialValue: this.state.jqrkfName,
                  })(
                    <Input style={{ width: 280 }}></Input>
                  )}
                </FormItem>
              </Form>
            </div>
          </div>
          <div style={{ margin: '50px 0px 100px 100px' }}>
            <Button onClick={this.quxiao} style={{ marginRight: 10 }}>取消</Button>
            <Button onClick={this.baocun} type='primary'>保存</Button>
          </div>
        </Spin>
      </div>
    );
  }

  baocun = () => {
    let userInfo = this.props.form.getFieldsValue();// 获取数据



    const { color, logob, logoc } = this.state
    this.props.form.validateFields((err, values) => {// 校验方法

      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'accessSettings/fetchf',
          payload: {
            voiceSynthesisFlag: Number(userInfo.yuyhc),
            voiceShowFlag: Number(userInfo.yuysran),
            winColor: color,
            robotHeadImg: logob,
            userHeadImg: logoc,
            robotName: userInfo.jqrkfName
          },
          callback: res => {

            if (res.code === 0) {
              message.success(`${res.msg}`);
              this.suax()
            }
          },
        });
      });
    })
  }

  suax = () => {
    this.setState({spinning:true})
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'accessSettings/fetchg',
        payload: {},
        callback: res => {


          this.setState({
            yuyhc: String(res.voiceSynthesisFlag),
            color: res.winColor,
            logob: res.userHeadImg,
            logoc: res.robotHeadImg,
            voiceShowFlag: String(res.yuysran),
            jqrkfName: res.robotName,
            spinning:false
          })
        },
      });
    });
  }

  quxiao = () => {
    this.props.form.setFields({ "jqrkfName": "" })
    this.props.form.setFields({ "yuyhc": "" })
    this.props.form.setFields({ "yuysran": "" })
    this.suax()
  }
}
export default connect(({ user }) => ({ // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(AppAccess));
